﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Web;
using NLBS.Framework;
using System.Reflection;
using System.IO;
using NLBS.Utility;
using System.Web.Caching;
using System.Web.UI;
namespace NLBS
{
    public class SiteConfig
    {
        public static XmlDocument GetExtensionsXml()
        {
            CheckExtensionsXmlFile();
            XmlDocument xml = new XmlDocument();
            xml.Load(HttpContext.Current.Server.MapPath("/App_Data/Extensions.xml"));
            return xml;
        }

        public static void SaveExtensionsXml(XmlDocument doc)
        {
            doc.Save(HttpContext.Current.Server.MapPath("/App_Data/Extensions.xml"));
        }

        public static void CreateExtensionsXmlFile()
        {
            if (!CheckExtensionsXmlFile())
            {
                XmlDocument doc = new XmlDocument();
                XmlElement root = doc.DocumentElement;
                doc.InsertBefore(doc.CreateXmlDeclaration("1.0", "utf-8", null), root);
                XmlElement pluginsNode = doc.CreateElement("Plugins");
                doc.AppendChild(pluginsNode);
                DirectoryInfo[] dirs = FileHelp.GetDirectory(HttpContext.Current.Server.MapPath("/Plugins"));
                foreach (DirectoryInfo item in dirs)
                {
                    XmlDocument plugindoc = new XmlDocument();
                    plugindoc.Load(HttpContext.Current.Server.MapPath("/Plugins/" + item.Name + "/Install.xml"));
                    XmlElement pluginNode = doc.CreateElement("Plugin");
                    pluginNode.InnerXml = plugindoc.DocumentElement.InnerXml;
                    pluginsNode.AppendChild(pluginNode);
                }
                SaveExtensionsXml(doc);
            }
        }

        #region Theme

        public static void CreateThemeXmlFile()
        {
            string path = HttpContext.Current.Server.MapPath("/App_Data/Themes.xml");

            XmlDocument doc = new XmlDocument();
            XmlElement root = doc.DocumentElement;
            doc.InsertBefore(doc.CreateXmlDeclaration("1.0", "utf-8", null), root);
            XmlElement themesNode = doc.CreateElement("Themes");
            doc.AppendChild(themesNode);
            DirectoryInfo[] dirs = FileHelp.GetDirectory(HttpContext.Current.Server.MapPath("/styles"));
            foreach (DirectoryInfo item in dirs)
            {
                if (File.Exists(HttpContext.Current.Server.MapPath("/styles/" + item.Name + "/theme.xml")))
                {
                    XmlDocument themedoc = new XmlDocument();
                    themedoc.Load(HttpContext.Current.Server.MapPath("/styles/" + item.Name + "/theme.xml"));
                    XmlElement themeNode = doc.CreateElement("Theme");
                    themeNode.InnerXml = themedoc.DocumentElement.InnerXml;
                    themesNode.AppendChild(themeNode);
                }
            }
            doc.Save(path);
        }

        public static XmlDocument GetThemeXml()
        {
            ContentCache cache = ContentCache.Instantiate();
            XmlDocument doc;
            if (cache["themeExtensions"] == null)
            {
                doc = new XmlDocument();

                string file = HttpContext.Current.Server.MapPath("/App_Data/Themes.xml");
                CacheDependency dep = new CacheDependency(file, DateTime.Now);
                doc.Load(file);
                cache.Insert("themeExtensions", doc, dep);
            }
            else
            {
                doc = (XmlDocument)cache["themeExtensions"];
            }
            return doc;
        }

        public static bool CheckThemeCount()
        {
            XmlDocument doc = GetThemeXml();
            DirectoryInfo[] dirs = FileHelp.GetDirectory(HttpContext.Current.Server.MapPath("/styles"));

            if (doc.DocumentElement.ChildNodes.Count != dirs.Length)
            {
                return false;
            }
            return true;
        }

        public static bool CheckThemeXmlFile()
        {
            return File.Exists(HttpContext.Current.Server.MapPath("/App_Data/Themes.xml"));
        }

        public static void GetTheme()
        {
            bool a = CheckThemeXmlFile();
            bool b = CheckThemeCount();
            if (!(a && b))
            {
                CreateThemeXmlFile();
            }
        }

        #endregion

        public static bool CheckExtensionsXmlFile()
        {
            return File.Exists(HttpContext.Current.Server.MapPath("/App_Data/Extensions.xml"));
        }

        public static XmlDocument GetWidgetXml()
        {
            ContentCache cache = ContentCache.Instantiate();
            XmlDocument doc;
            if (cache["widgetExtensions"] == null)
            {
                doc = new XmlDocument();

                string file = HttpContext.Current.Server.MapPath("/App_Data/Widget.xml");
                CacheDependency dep = new CacheDependency(file, DateTime.Now);
                doc.Load(file);
                cache.Insert("widgetExtensions", doc, dep);
            }
            else
            {
                doc = (XmlDocument)cache["widgetExtensions"];
            }
            return doc;
        }

        public static XmlDocument GetLinksXml()
        {
            ContentCache cache = ContentCache.Instantiate();
            XmlDocument doc;
            if (cache["linksExtensions"] == null)
            {
                doc = new XmlDocument();

                string file = HttpContext.Current.Server.MapPath("/App_Data/Links.xml");
                CacheDependency dep = new CacheDependency(file, DateTime.Now);
                doc.Load(file);
                cache.Insert("linksExtensions", doc, dep);
            }
            else
            {
                doc = (XmlDocument)cache["linksExtensions"];
            }
            return doc;
        }

        public static string GetLinks(string linkType)
        {
            XmlDocument doc = GetLinksXml();
            XmlNode root = doc.DocumentElement;
            foreach (XmlNode item in root.ChildNodes)
            {
                if (item.Attributes["LinkType"].Value == linkType)
                {
                    return item.InnerText;
                }
            }

            return string.Empty;
        }

        public static XmlDocument GetResourceXml()
        {
            XmlDocument doc = new XmlDocument();
            ContentCache contentCache = ContentCache.Instantiate();
            if (contentCache["ResourceXml"] != null)
            {
                doc = (XmlDocument)contentCache["ResourceXml"];
            }
            else
            {
                string file = HttpContext.Current.Server.MapPath("/App_Data/Resource.xml");
                doc.Load(file);
                CacheDependency dep = new CacheDependency(file, DateTime.Now);
                contentCache.Insert("ResourceXml", doc, dep);
            }
            return doc;
        }

        public static void RegsiterResource()
        {
            XmlDocument doc = SiteConfig.GetResourceXml();

            XmlNode firstNode = doc.DocumentElement.FirstChild;
            XmlNodeList RequiredScripts = firstNode.FirstChild.ChildNodes;
            XmlNodeList RequiredStyles = firstNode.ChildNodes[1].ChildNodes;


            RegisterResource(RequiredScripts, RequiredStyles);

            Page currentPage = GlobalData.CurrentPage;
            XmlNode secondNode = doc.DocumentElement.ChildNodes[1];
            foreach (XmlNode item in secondNode.ChildNodes)
            {

                string pageSrc = item.Attributes["Src"].Value.ToLower();
                if (currentPage.ResolveUrl(pageSrc) == HttpContext.Current.Request.Path.ToLower())
                {
                    RegisterResource(item.FirstChild.ChildNodes, item.ChildNodes[1].ChildNodes);
                }
            }
        }

        private static void RegisterResource(XmlNodeList scripts, XmlNodeList styles)
        {
            Page currentPage = GlobalData.CurrentPage;
            foreach (XmlNode item in styles)
            {
                string href = currentPage.ResolveUrl(item.Attributes["Href"].Value);
                LiteralControl control = new LiteralControl(string.Format("<link href=\"{0}\" rel=\"stylesheet\" type=\"text/css\" />", href));
                currentPage.Header.Controls.Add(control);
            }
            foreach (XmlNode item in scripts)
            {

                string key = item.Attributes["Key"].Value;
                string src = currentPage.ResolveUrl(item.Attributes["Src"].Value);
                string position = item.Attributes["Position"].Value;
                if (position == "header")
                {
                    ScriptManager.RegisterClientScriptInclude(currentPage, currentPage.GetType(), key, src);
                }
            }
        }
    }
}


            //       Assembly a = Assembly.Load("NLBS.Blog");
            //Type[] types = a.GetTypes();
            //string aa = string.Empty;
            //foreach (Type type in types)
            //{
            //    object[] attributes = type.GetCustomAttributes(typeof(ExtensionAttribute), false);

            //    foreach (object attribute in attributes)
            //    {
            //        a.CreateInstance(type.FullName);
            //    }
            //}